package com.avic.modules.historicalData.service.impl;

import com.avic.modules.equipment.domain.Equipment;
import com.avic.modules.equipment.domain.EquipmentCategory;
import com.avic.modules.equipment.service.mapper.EquipmentCategoryMapper;
import com.avic.modules.equipment.service.mapper.EquipmentMapper;
import com.avic.modules.historicalData.rest.HistoricalData;
import com.avic.modules.historicalData.service.HistoricalDataService;
import com.avic.modules.mapping.domain.DataMapping;
import com.avic.modules.mapping.service.DataMappingService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class HistoricalDataServiceImpl implements HistoricalDataService {

    private final EquipmentCategoryMapper equipmentCategoryMapper;
    private final EquipmentMapper equipmentMapper;
    private final DataMappingService dataMappingService;

    @Value("${spring.datasource.druid.url}")
    private String CONN_URL;
    @Value("${spring.datasource.druid.username}")
    private String USER;
    @Value("${spring.datasource.druid.password}")
    private String PASS;
    private final String DRIVER = "com.mysql.cj.jdbc.Driver";

    public HistoricalDataServiceImpl(EquipmentCategoryMapper equipmentCategoryMapper, EquipmentMapper equipmentMapper, DataMappingService dataMappingService) {
        this.equipmentCategoryMapper = equipmentCategoryMapper;
        this.equipmentMapper = equipmentMapper;
        this.dataMappingService = dataMappingService;
    }

    @Override
    public void del() throws SQLException {
        Connection connection = getConnection();
        Statement statement = connection.createStatement();
        QueryWrapper<EquipmentCategory> criteria = new QueryWrapper<>();
        List<EquipmentCategory> equipmentCategories = equipmentCategoryMapper.selectList(criteria);

        List<String> stringList = new ArrayList<>();
        String name = "TRUNCATE TABLE equipment_data_";
        for(EquipmentCategory equip:equipmentCategories){
            stringList.add(name+equip.getEnglishName());
        }
        for(String s:stringList){
            statement.execute(s);
        }
    }

    @Override
    public void add() throws SQLException {
        Connection connection = getConnection();
        Statement statement = connection.createStatement();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = new Date();
        String today = format.format(date);

        List<String> stringList = new ArrayList<>();
        QueryWrapper<EquipmentCategory> criteria = new QueryWrapper<>();
        List<EquipmentCategory> equipmentCategories = equipmentCategoryMapper.selectList(criteria);
        for(EquipmentCategory category:equipmentCategories){
            List<HistoricalData> list = new ArrayList<>();
            String name = "insert into equipment_data_";
            name = name + category.getEnglishName();
            String state = "(" + "time,";
            String end = "(" + "'" + today + "'," ;
            QueryWrapper<Equipment> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("equip_category_id", category.getId());
            List<Equipment> equipment = equipmentMapper.selectList(queryWrapper);
            for(Equipment equip:equipment){
                List<DataMapping> dataMappings = dataMappingService.selectEquipMapping(equip.getId(), category.getId());
                for(DataMapping map:dataMappings){

                    if(map.getTagName()!=null && !map.getTagName().equals("") && map.getValue()!=null && !map.getValue().equals("")){
                        HistoricalData historicalData = new HistoricalData();
                        historicalData.setName(map.getTagName());
                        String value = map.getValue();
                        if(value.equalsIgnoreCase("true")){
                            map.setValue("1");
                        }else if(value.equalsIgnoreCase("false")){
                            map.setValue("0");
                        }
                        double v = Double.parseDouble(map.getValue());
                        historicalData.setValue(v);
                        list.add(historicalData);
                    }
                }
            }

            for(HistoricalData historical:list){
                state += historical.getName() + ",";
                end += "'" + historical.getValue() + "',";
            }

            if(state.substring(state.length()-1).equals(",")){
                state = state.substring(0,state.length() - 1);
            }
            if(end.substring(end.length()-1).equals(",")){
                end = end.substring(0,end.length() - 1);
            }
            String total = name + state + ")values" + end + ")";
            stringList.add(total);
        }
        for(String s:stringList){
            statement.execute(s);
        }
    }

    private Connection getConnection(){
        Connection connection = null;
        try{
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try{
            connection = DriverManager.getConnection(CONN_URL,USER, PASS);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return connection;
    }
}
